﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Linq;
using System.IO;
using System.Configuration;
using DGBY.BLL;
using GoldPrinter;
using WeifenLuo.WinFormsUI.Docking;
using System.Management;
using System.Drawing.Printing;
using CommonData.Log;
using System.Net;
using Updater.Core;
using System.Diagnostics;
using WHC.Security.Entity;
using WHC.Security.Common;
using System.Runtime.InteropServices;
namespace BYManageInfoSystem
{
    public partial class Frm_Main : Form
    {
        [DllImport("user32.dll")]
        private static extern int GetSystemMenu(int hwnd, int bRevert);
        [DllImport("User32.dll")]
        private static extern int GetMenuItemCount(int hMenu);
        [DllImport("User32.dll")]
        private static extern int RemoveMenu(int hMenu, int nPosition, int wFlags);
        [DllImport("User32.dll")]
        private static extern int DrawMenuBar(int hwnd);

        private const int MF_BYPOSITION = 0x400;
        private const int MF_DISABLED = 0x2;
        private static DateTime m_dtServerSingle = DateTime.Parse("1900-01-01");
        public static Dictionary<string, Dictionary<string, string>> m_dicFormText2FormTypeName = new Dictionary<string, Dictionary<string, string>>();
        private List<FunctionInfo> m_lstOneLevelFunRuntime = new List<FunctionInfo>();
        private WHC.Security.BLL.Function function = new WHC.Security.BLL.Function();
        //public static int m_nLoginUserId = 0;
        //private static TrainingDB.BLL.CK_OperLogTab m_bllDG_OperLogTab = new TrainingDB.BLL.CK_OperLogTab();
        public static Dictionary<string, string> m_dicModuleHelpWnd = new Dictionary<string, string>();
        private static List<FunctionInfo> m_UserFunList = new List<FunctionInfo>();
        
        private string m_strSql = "";
        private DGBY.BLL.T_ACL_User m_bllT_ACL_User = new DGBY.BLL.T_ACL_User();
        private int m_nTipTimes = 3;
        public static string m_strVersion = ConfigurationSettings.AppSettings["Version"];
        private static DGBY.BLL.DG_OperLogTab m_bllDG_OperLogTab = new DGBY.BLL.DG_OperLogTab();
        private DGBY.BLL.VersionTab m_bllVersionTab = new DGBY.BLL.VersionTab();
        private DGBY.BLL.DiscountTab m_bllDiscountTab = new DGBY.BLL.DiscountTab();
        private DGBY.BLL.TYInvoiceTab m_bllTYInvoiceTab = new DGBY.BLL.TYInvoiceTab();
        private DGBY.BLL.BGCKHTTab m_bllBGCKHTTab = new DGBY.BLL.BGCKHTTab();
        private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();
        private Frm_BGDComeBack frm_bgdcomebacke = new Frm_BGDComeBack();
       // private DGBY.BLL.BGDComeBackTab m_bllBGDComeBackTab = new DGBY.BLL.BGDComeBackTab();
        private DGBY.BLL.BGPackingTab m_bllBGPackingTab = new DGBY.BLL.BGPackingTab();
        private DGBY.BLL.SJPackGoodsMXTab m_bllSJPackGoodsMXTab = new DGBY.BLL.SJPackGoodsMXTab();
        private DGBY.BLL.SJPackingTab m_bllSJPackingTab = new DGBY.BLL.SJPackingTab();
        private DGBY.BLL.FeeSJTruePayTab m_bllFeeSJTruePayTab = new DGBY.BLL.FeeSJTruePayTab();
        //public static ExcelBase m_printExcelBase = new ExcelBase();
        //public static int m_nContractSelectIndex = 0;
        public static int m_nContractSelectValue = 0;
        private bool m_bLoginSuccess = false;
        public static bool m_bCompleteVer = false;
        private Frm_MainToolWindowNew mainToolWin = null;
        public static DGBY.BLL.TaoDaPrinterNameTab bllTaoDaPrinterNameTab = new DGBY.BLL.TaoDaPrinterNameTab();
        public static DGBY.BLL.BYCompanyTab bllBYCompanyTab = new DGBY.BLL.BYCompanyTab();
        //public static DGBY.BLL.Accounts_PermissionCategories bllAccounts_PermissionCategories = new DGBY.BLL.Accounts_PermissionCategories();
        //public static DGBY.BLL.Accounts_Permissions bllAccounts_Permissions = new DGBY.BLL.Accounts_Permissions();
        private static DGBY.BLL.PaidanRegisterTab m_bllPaidanRegisterTab = new DGBY.BLL.PaidanRegisterTab();


        //private DGBY.BLL.Accounts_RolePermissions m_bllAccounts_RolePermissions = new DGBY.BLL.Accounts_RolePermissions();
        private DGBY.BLL.T_ACL_User m_bllUserPasswordTab = new DGBY.BLL.T_ACL_User();
        //private DGBY.BLL.Accounts_UserRoles m_bllAccounts_UserRoles = new DGBY.BLL.Accounts_UserRoles();
        public static string m_strLoginUser = "";
        public static List<string> m_lstPermitPerson = new List<string>();
        
        public static int m_nLoginUserId = 0;
        public static decimal m_dtDiscountFactor = 0;
        public static readonly int m_nEmptyDanID = 127;
        List<string> lstPerm = new List<string>();
        private static Frm_Main m_Frm_Main = null;
        
        //private Dictionary<string, string> m_dicFormText2FormTypeName = new Dictionary<string, string>();
        private static string m_strWindowName = "";
        public static void DisableCloseButton(System.Windows.Forms.Form form)
        {
            int hMenu, nCount;

            // Get handle to system menu.
            hMenu = GetSystemMenu(form.Handle.ToInt32(), 0);
            // Get number of items in the menu
            nCount = GetMenuItemCount(hMenu);
            // Remoe the last item from system menu (last item is 'Close')
            RemoveMenu(hMenu, nCount - 1, MF_DISABLED | MF_BYPOSITION);
            // Redraw the menu
            DrawMenuBar(form.Handle.ToInt32());
        }
        public static bool CheckPerm(string strModuleName, string strOperName)
        {
            bool bRet = false;
            string strTemp = strModuleName + "_" + strOperName;
            foreach (FunctionInfo f in m_UserFunList)
            {
                if (f.Name.Equals(strTemp))
                {
                    bRet = true;
                    break;
                }
            }
            return bRet;
        }
        public static void contextMenu1_Popup(object sender, EventArgs e)
        {
            ContextMenu cm = (ContextMenu)sender;
            m_strWindowName = cm.Tag.ToString();

            if (cm.MenuItems.Count == 0)
            {

                cm.MenuItems.Add("关闭全部窗体", new System.EventHandler(CloseAllWindows));
                cm.MenuItems.Add("关闭其他窗体", new System.EventHandler(CloseOtherWindows));
                cm.MenuItems.Add("关闭当前窗体", new System.EventHandler(CloseCurrentWindows));
            }

        }
        private static void CloseAllWindows(object sender, EventArgs e)
        {
            //string s = (string)e;
            foreach (Form mdiChildFrm in m_Frm_Main.MdiChildren)
            {
                mdiChildFrm.Close();
            }
        }
        private static void CloseOtherWindows(object sender, EventArgs e)
        {
            foreach (Form mdiChildFrm in m_Frm_Main.MdiChildren)
            {
                if (mdiChildFrm.Text != m_strWindowName)
                    mdiChildFrm.Close();
            }
        }
        private static void CloseCurrentWindows(object sender, EventArgs e)
        {
            foreach (Form mdiChildFrm in m_Frm_Main.MdiChildren)
            {
                if (mdiChildFrm.Text == m_strWindowName)
                    mdiChildFrm.Close();
            }
        }
       // static Log m_log = null;
        public static void LogInfo(string strInfo)
        {
           // LogMessage lmsg = new LogMessage(strInfo, MessageType.Error);
           // m_log.Write(lmsg);
        }

        public static void Log2DB(string strModuleName, string strOperName, string DanjuNameOrNo)
        {
            DGBY.Model.DG_OperLogTab modelDG_OperLogTab = new DGBY.Model.DG_OperLogTab();
            modelDG_OperLogTab.OperDate = System.DateTime.Now;
            modelDG_OperLogTab.UserPasswordTabID = m_nLoginUserId;
            modelDG_OperLogTab.OperName = strOperName;
            modelDG_OperLogTab.ModuleName = strModuleName;

            if (DanjuNameOrNo.Length >= 200)
                DanjuNameOrNo = DanjuNameOrNo.Substring(0, 200);

            modelDG_OperLogTab.DanjuNameOrNo = DanjuNameOrNo;

            m_bllDG_OperLogTab.Add(modelDG_OperLogTab);
        }

        public static void WriteLog(string sMsg)
        {
            if (sMsg != "")
            {
                string strTemp = System.Windows.Forms.Application.StartupPath + @"\log.txt";
                string filename = strTemp;
                System.DateTime dt = System.DateTime.Now;
                try
                {
                    FileInfo fi = new FileInfo(filename);
                    UTF8Encoding utf8 = new UTF8Encoding(true);
                    if (!fi.Exists)
                    {
                        using (StreamWriter sw = new StreamWriter(filename, false, utf8))
                        {
                            sw.WriteLine(dt.ToString() + "@@" + sMsg);
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = new StreamWriter(filename, true, utf8))
                        {
                            sw.WriteLine(dt.ToString() + ":" + sMsg);
                            sw.Close();
                        }
                    }
                }
                catch
                {
                }
            }
        }

        private void BindComp2Fac()
        {
            DataSet ds = m_bllPaidanRegisterTab.GetListEx("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    int nFactoryDataTabID = Convert.ToInt32(ds.Tables[0].Rows[i]["FactoryDataTabID"].ToString(), 10);
                    int nBYCompanyTabID = Convert.ToInt32(ds.Tables[0].Rows[i]["BYCompanyTabID"].ToString(), 10);

                    DGBY.Model.FactoryDataTab modelFactoryDataTabOld = m_bllFactoryDataTab.GetModel(nFactoryDataTabID);
                    modelFactoryDataTabOld.BYCompanyTabID = nBYCompanyTabID;
                    m_bllFactoryDataTab.Update(modelFactoryDataTabOld);

                }
            }
        }


        private void InitActivePrinterName()
        {
            try
            {
                DataSet ds = bllTaoDaPrinterNameTab.GetList("");
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {

                }
                else
                {
                    ExcelBase eB = new ExcelBase();
                    string strPrinterName = eB.GetActivePrinterNameWithPort();
                    eB.Close();
                    DGBY.Model.TaoDaPrinterNameTab modelTaoDaPrinterNameTab = new DGBY.Model.TaoDaPrinterNameTab();
                    modelTaoDaPrinterNameTab.TaoDaPrinterName = strPrinterName;
                    bllTaoDaPrinterNameTab.Add(modelTaoDaPrinterNameTab);
                }
            }
            catch (System.Exception ex)
            {

            }
            
        }



        private void notifyMenu_Show_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Maximized;
                this.Show();
                this.BringToFront();
                this.Activate();
                this.Focus();
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
            }
        }

        private void notifyMenu_Exit_Click(object sender, EventArgs e)
        {

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            notifyMenu_Show_Click(sender, e);
        }

        private void MainForm_MaximizedBoundsChanged(object sender, EventArgs e)
        {
            this.Hide();
        }
        
        /// <summary>
        /// 缩小到托盘中，不退出
        /// </summary>
        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Frm_Main.m_bCompleteVer == false)
                return;
            //如果我们操作【×】按钮，那么不关闭程序而是缩小化到托盘，并提示用户.
            //if (this.WindowState != FormWindowState.Minimized && m_bLoginSuccess)
            //{
            //    e.Cancel = true;//不关闭程序
            //    this.Hide();
            //    //最小化到托盘的时候显示图标提示信息，提示用户并未关闭程序
            //    this.WindowState = FormWindowState.Minimized;
            //    notifyIcon1.ShowBalloonTip(3000, "程序最小化提示",
            //         "图标已经缩小到托盘，打开窗口请双击图标即可。",
            //         ToolTipIcon.Info);
            //    return;
            //}

           
            foreach (Form mdiChildFrm in this.MdiChildren)
            {
                mdiChildFrm.Close();
            }
          //  m_printExcelBase.Close();
        }

        private void Frm_Main_Move(object sender, EventArgs e)
        {
            //if (this == null)
            //{
            //    return;
            //}

            ////最小化到托盘的时候显示图标提示信息
            //if (this.WindowState == FormWindowState.Minimized)
            //{
            //    this.Hide();
            //    notifyIcon1.ShowBalloonTip(3000, "程序最小化提示",
            //        "图标已经缩小到托盘，打开窗口请双击图标即可。右键退出系统",
            //        ToolTipIcon.Info);
            //}
        }

        public static Frm_Main GetMainForm()
        {
            if(m_Frm_Main == null)
            {
                m_Frm_Main = new Frm_Main();
            }

            return m_Frm_Main;
        }
        private Frm_Main()
        {
            Frm_Main.m_bCompleteVer = true;
            InitializeComponent();
            InitFormText2FormType();
            InitModuleHelpWnd();
            InitFirstLevelFun();
            InitSecondLevelFun();
        }
        //private void ControlsInPanelEnable(Form1 form)
        //{
        //    foreach (ToolStripItem vItem in form.toolStrip1.Items)
        //    {
        //        if (vItem is ToolStripButton)
        //            Console.WriteLine(vItem.Text);
        //    }
        //}
      
        public void Notify(string caption, string content)
        {
            Notify(caption, content, 400, 200, 5000);
        }

        /// <summary>
        /// 弹出提示消息窗口
        /// </summary>
        public static void Notify(string caption, string content, int width, int height, int waitTime)
        {
            NotifyWindow notifyWindow = new NotifyWindow(caption, content);
            //notifyWindow.TitleClicked += new System.EventHandler(notifyWindowClick);
            //notifyWindow.TextClicked += new EventHandler(notifyWindowClick);
            notifyWindow.SetDimensions(width, height);
            notifyWindow.WaitTime = waitTime;
            notifyWindow.Notify();
        }

        private void DevelopVersion()
        {
            this.dockPanel.BackgroundImage = null;
            Frm_Main.m_bCompleteVer = true;
            m_bLoginSuccess = true;
            mainToolWin = new Frm_MainToolWindowNew();
            mainToolWin.Show(this.dockPanel, DockState.DockLeft);
            InitFormText2FormTypeNameDic();

            this.dockPanel.DockLeftPortion = 0.17;
            m_nContractSelectValue = m_bllPaidanRegisterTab.GetMaxId() - 1;
        }

        private void UpdateDatabase()
        {
            if (m_strSql != "")
            {
                m_bllSJPackingTab.ExecuteSql(m_strSql);
                Frm_Main.Log2DB(this.Text, "更新数据库", m_strSql);
            }
            
            MessageBox.Show("数据库更新成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        private void TryUpdateVersion()
        {
            UpdateClass update = new UpdateClass();
            try
            {
                bool newVersion = update.HasNewVersion;
                if (newVersion)
                {
                    Updater.Core.Manifest[] m = update.CheckForUpdates();
                    string strNewVersion = m[0].Version;

                    if (MessageBox.Show("有新的版本，是否需要更新", "更新提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string strSql = @"update VersionTab set VersionNo =  '" + strNewVersion + "' where VersionTab.VersionTabid = 1";
                        m_bllSJPackingTab.ExecuteSql(strSql);
                        Process.Start(Path.Combine(Application.StartupPath, "Updater.exe"), "121");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        
        //private void Frm_Main_Load(object sender, EventArgs e)
        //{


        //    //DevelopVersion();
        //    //return;
      
        //    m_nContractSelectValue = m_bllPaidanRegisterTab.GetMaxId() - 1;
        //    //this.dockPanel.BackgroundImage = null;
        //    m_lstPermitPerson.Add("吴婉玲");
        //    m_lstPermitPerson.Add("卢丽平");
        //    m_lstPermitPerson.Add("钟运甜");
        //    m_lstPermitPerson.Add("陈洁薇");
        //    m_lstPermitPerson.Add("林淦坤");
        //    m_lstPermitPerson.Add("赖泽文");
        //    m_lstPermitPerson.Add("梁青媚");
        //    m_lstPermitPerson.Add("宋波");
        //    InitActivePrinterName();
        //    DataSet ds = m_bllVersionTab.GetList("");
        //    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //    {
        //        string strVer = ds.Tables[0].Rows[0]["VersionNo"].ToString();
        //        UpdaterConfigurationView updateCfgView = new UpdaterConfigurationView();
        //        string strTemp = updateCfgView.Version;
        //        if (strVer != strTemp)
        //        {
        //            MessageBox.Show("请使用最新版本的程序登录！" + "数据库最新版本" + strVer + "您当前版本" + strTemp, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //            Application.Exit();
        //            return;
        //        }
        //        else
        //        {
        //            this.Text += "Ver" + strVer;
        //        }

        //    }

        //    //ClassBackUpDataBase fBack = new ClassBackUpDataBase();
        //    //fBack.Start();
        //    //CheckMenu(menuStripMain);

        //  //  m_bLoginSuccess = true;



        //    //Frm_MainNew.m_bCompleteVer = true;
        //    Frm_Login frm_login = new Frm_Login();

        //    if (frm_login.ShowDialog() == DialogResult.OK)
        //    {
        //        m_strLoginUser = frm_login.comboBoxOrderPerson.Text;
        //        this.Text += @"-" + m_strLoginUser;
        //        ds = m_bllT_ACL_User.GetList("T_ACL_User.UserName = '" + m_strLoginUser + "'");
        //        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //        {
        //            m_nLoginUserId = Convert.ToInt32(ds.Tables[0].Rows[0]["UserPasswordTabID"].ToString());
        //            //Frm_MainNew.Notify("登录成功", "欢迎" + m_strLoginUser, 300, 200, 3000);
        //            m_bLoginSuccess = true;
        //            //  m_log = new Log(m_strLoginUser);
        //            this.timer1.Start();
        //            // backgroundWorker1.RunWorkerAsync();
        //            DGBY.Model.DiscountTab modelDiscountTab = m_bllDiscountTab.GetModel(1);
        //            m_dtDiscountFactor = modelDiscountTab.DiscountFactor;
        //        }
        //        else
        //        {
        //            Application.Exit();
        //        }

        //        bool bTest = m_bCompleteVer;

        //    }
        //    else
        //    {
        //        Application.Exit();
        //    }

        //    if (Frm_MainNew.m_strLoginUser == "宋波")
        //    {
        //        TryUpdateVersion();
        //    }

        //    mainToolWin = new Frm_MainToolWindowNew();
        //    mainToolWin.Show(this.dockPanel, DockState.DockLeft);
        //    InitFormText2FormTypeNameDic();

        //    this.dockPanel.DockLeftPortion = 0.17;


        //    if (Frm_MainNew.m_bCompleteVer == false)
        //        this.提单管理ToolStripMenuItem.Visible = false;
        //    else
        //        this.提单管理ToolStripMenuItem.Visible = true;


        //    //Frm_Login frm_login = new Frm_Login();

        //    //if (frm_login.ShowDialog() == DialogResult.OK)
        //    //{
        //    //    m_strLoginUser = frm_login.textBox_username.Text;
        //    //    this.Text += @"-" + m_strLoginUser;

        //    //    DataSet ds = m_bllAccounts_UserRoles.GetRoleList("T_ACL_User.UserName = '" + m_strLoginUser + "'");

        //    //    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //    //    {
        //    //        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        //    //        {
        //    //            int nID = Convert.ToInt32(ds.Tables[i].Rows[0]["角色ID"].ToString());
        //    //            DataSet ds2 = m_bllAccounts_RolePermissions.GetListWithCate("Accounts_RolesID = '" + nID.ToString() + "'");
        //    //            if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
        //    //            {
        //    //                for (int j = 0; j < ds2.Tables[0].Rows.Count; j++)
        //    //                {
        //    //                    string strPerm = ds2.Tables[0].Rows[j]["权限名称"].ToString();
        //    //                    lstPerm.Add(strPerm);
        //    //                }
        //    //            }
        //    //        }
        //    //    }
        //    //    DisableToolStripButton(this.toolStrip1);
        //    //    DisableMenu(menuStripMain);
        //    //    return;
        //    //}
        //    //else
        //    //{
        //    //    Application.Exit();
        //    //}
           
        //}

      
     
        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text != "权限管理" 
                && e.ClickedItem.Text != "套打打印机设置"
                && e.ClickedItem.Text != "系统数据处理")
                ShowContent(e.ClickedItem.Text.ToString());

        }

     
        private void menu_Window_CloseAll_Click(object sender, EventArgs e)
        {
            CloseAllDocuments();
        }

        private void menu_Window_CloseOther_Click(object sender, EventArgs e)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                Form activeMdi = ActiveMdiChild;
                foreach (Form form in MdiChildren)
                {
                    if (form != activeMdi)
                    {
                        form.Close();
                    }
                }
            }
            else
            {
                foreach (IDockContent document in dockPanel.DocumentsToArray())
                {
                    if (!document.DockHandler.IsActivated)
                    {
                        document.DockHandler.Close();
                    }
                }
            }
        }

     

        public void CloseAllDocuments()
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                foreach (Form form in MdiChildren)
                {
                    form.Close();
                }
            }
            else
            {
                IDockContent[] documents = dockPanel.DocumentsToArray();
                foreach (IDockContent content in documents)
                {
                    content.DockHandler.Close();
                }
            }
        } 
        private void toolStripButtonPaiDan_Click(object sender, EventArgs e)
        {

        }
 


        ///<summary>
        ///打开窗体
        ///</summary>
        ///<param name="mdiChildTypeString"></param>
        ///<returns></returns>     
        ///
        private void ShowWindow(string mdiChildTypeString)
        {

             Form currentMdiChild=null;

            if(!IsMDIChildFormExist(mdiChildTypeString))
             {
                 Assembly assembly=Assembly.GetExecutingAssembly();
                 Type typForm=assembly.GetType(mdiChildTypeString);

                //关于InvokeMember用法，不明白的可以查看：http://msdn.microsoft.com/zh-cn/library/de3dhzwy(VS.80).aspx
                 Object mdiChild=typForm.InvokeMember(
                    null,
                     BindingFlags.DeclaredOnly|BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.CreateInstance,
                    null,
                    null,
                    null);

                if(mdiChild!=null)
                 {
                     currentMdiChild=mdiChild as Form;
                     currentMdiChild.MdiParent=this;
                     currentMdiChild.WindowState=FormWindowState.Maximized;
                     currentMdiChild.Show();
                     currentMdiChild.Focus();
                 }

             }

        }

        ///<summary>
        ///检查MDI子窗体是否存在
        ///</summary>
        ///<param name="mdiChildTypeString"></param>
        ///<returns></returns>        
        private bool IsMDIChildFormExist(string mdiChildTypeString)
        {
             Form currentMDIChild=null;
            foreach(Form mdiChildFrm in this.MdiChildren)
             {
                if(mdiChildFrm.GetType().ToString()==mdiChildTypeString)
                 {
                     currentMDIChild=mdiChildFrm;
                    break;
                 }
             }

            if(currentMDIChild!=null)
             {
                if(currentMDIChild.WindowState==FormWindowState.Minimized)
                 {
                     currentMDIChild.WindowState=FormWindowState.Normal;
                 }
                 currentMDIChild.TopMost=true;
                 currentMDIChild.Activate();
                 currentMDIChild.Focus();
                return true;
             }
            else
             {
                return false;
             }

        }

       
        public void ShowSJFillBoxSheetForm()
        {
            DockContent frm = FindDocument("商检装箱单管理");
            if (frm != null)
            {
                frm = ShowContent("商检装箱单管理");
                return;
                // frm = ChildWinManagement.LoadMdiForm(Portal.gc.MainDialog, formType) as DockContent;
            }
            frm = new Frm_CommerCheckFillBoxSheet();

            frm.Show(this.dockPanel);
        }
        public void ShowSJContractForm()
        {
            DockContent frm = FindDocument("商检出口合同");
            if (frm != null)
            {
                frm = ShowContent("商检出口合同");
                return;
                // frm = ChildWinManagement.LoadMdiForm(Portal.gc.MainDialog, formType) as DockContent;
            }
            frm = new Frm_CommerCheckOutPutContract();

            frm.Show(this.dockPanel);
        }
        public void ShowSJBuyGoodsForm()
        {
            DockContent frm = FindDocument("购货合同草稿");
            if (frm != null)
            {
                frm = ShowContent("购货合同草稿");
                return;
                // frm = ChildWinManagement.LoadMdiForm(Portal.gc.MainDialog, formType) as DockContent;
            }
            frm = new Frm_CommerCheckBuyGoodsContract();

            frm.Show(this.dockPanel);
        }

        private void 退出系统ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.ShowInTaskbar = false;
            m_bLoginSuccess = false;
            this.Close();
            //Environment.Exit(1);//退出程序
        }

        private void ToolStripMenuItemCheck_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonBGCK_Click(object sender, EventArgs e)
        {
            WHC.Security.UI.Portal.StartLogin();
        }

        private void 海关管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Frm_HaiGuan frm_HaiGuan = new Frm_HaiGuan();
            frm_HaiGuan.StartPosition = FormStartPosition.CenterScreen;
            frm_HaiGuan.ShowDialog();
        }

        private void 开票汇率录入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Frm_BatchKaiPiaoHuiLv frm_BatchKaiPiaoHuiLv = new Frm_BatchKaiPiaoHuiLv();
            frm_BatchKaiPiaoHuiLv.StartPosition = FormStartPosition.CenterScreen;
            frm_BatchKaiPiaoHuiLv.ShowDialog();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            DataSet ds = m_bllPaidanRegisterTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    int nPaidanRegisterTabID = Convert.ToInt32(ds.Tables[0].Rows[i]["PaidanRegisterTabID"].ToString(), 10);
                    DGBY.Model.TYInvoiceTab modelTYInvoiceTab = new DGBY.Model.TYInvoiceTab();
                    modelTYInvoiceTab.PaidanRegisterTabID = nPaidanRegisterTabID;
                    modelTYInvoiceTab.ZhuanYPort = "";
                    modelTYInvoiceTab.JieHuiFSTabID = 1;
                    modelTYInvoiceTab.MaoYiFSTabID = 1;
                    modelTYInvoiceTab.Note = "";
                    modelTYInvoiceTab.LCNo = "";
                    modelTYInvoiceTab.KPDate = System.DateTime.Now;
                    modelTYInvoiceTab.BYCompBankCountTabID = 1;

                    m_bllTYInvoiceTab.Add(modelTYInvoiceTab);
                }
            }

            //DateTime dt = System.DateTime.Today;
            //DataSet ds = m_bllPaidanRegisterTab.GetAllPaiDanList("PaiDanDate >= " + "'" + dt.AddDays(-50) + "'" + " and PaiDanDate <= " + "'" + dt + "'");
            //if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            //{
            //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //    {
            //        frm_bgdcomebacke.SyncBGDComeBackMX(ds.Tables[0].Rows[i]["合同编号"].ToString());
            //    }
            //}

            return;
            
        }

        
        #region 读写配置文件
        /// <summary>
        /// 修改配置文件中某项的值
        /// </summary>
        /// <param name="key">appSettings的key</param>
        /// <param name="value">appSettings的Value</param>
        public static void SetConfig(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (config.AppSettings.Settings[key] != null)
                config.AppSettings.Settings[key].Value = value;
            else
                config.AppSettings.Settings.Add(key, value);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 读取配置文件某项的值
        /// </summary>
        /// <param name="key">appSettings的key</param>
        /// <returns>appSettings的Value</returns>
        public static string GetConfig(string key)
        {
            string _value = string.Empty;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
            {
                _value = config.AppSettings.Settings[key].Value;
            }
            return _value;
        }
        #endregion
        private void 生成版本号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now.Date;
            string strVer = dt.ToLongDateString().ToString();
            SetConfig("Version", strVer);
            
            //cfg.ConfigurationSettings.AppSettings["Version"] = strVer;
        }

        private void 查看当前版本号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strTemp = GetConfig("Version");
            MessageBox.Show("当前的版本号是" + strTemp, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (m_nTipTimes <= 0)
            {
                MessageBox.Show("你的版本已过期，程序即将退出！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
            DataSet ds = m_bllVersionTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                string strVer = ds.Tables[0].Rows[0]["VersionNo"].ToString();
                UpdaterConfigurationView updateCfgView = new UpdaterConfigurationView();
                string strTemp = updateCfgView.Version;
                //string strTemp = GetConfig("Version");
                if (strVer != strTemp)
                {
                    m_nTipTimes--;
                    MessageBox.Show("你的版本已过期，请尽快使用最新版本的程序登录！每隔5分钟提醒一次，" + m_nTipTimes.ToString() + "次提醒后程序将自动退出！",  "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

            }
        }

       

        private void toolStripButtonJZX_Click(object sender, EventArgs e)
        {
            if (Frm_Main.m_strLoginUser == "宋波")
            {
                UpdateDatabase();
            }
        }

        private void 新权限管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WHC.Security.UI.Portal.StartLogin();
        }
       
          
   
        //新权限管理开始
        private void InitFormText2FormType()
        {
            Dictionary<string, string> dicCSharpBase = new Dictionary<string, string>();
            dicCSharpBase.Add("工厂管理", "BYManageInfoSystem.Frm_FactoryInfo");
            dicCSharpBase.Add("经营单位管理", "BYManageInfoSystem.Frm_SelfCompMng");
            dicCSharpBase.Add("部门管理", "BYManageInfoSystem.Frm_BYDeptInfo");
            dicCSharpBase.Add("每月汇率管理", "BYManageInfoSystem.Frm_MonthRateReference");
            dicCSharpBase.Add("结汇管理", "BYManageInfoSystem.Frm_JieHui");
            dicCSharpBase.Add("货品种类管理", "BYManageInfoSystem.Frm_FacGoodsCate");
            dicCSharpBase.Add("报关港管理", "BYManageInfoSystem.Frm_BGPort");
            dicCSharpBase.Add("单证种类管理", "BYManageInfoSystem.Frm_DZCateInfo");
            dicCSharpBase.Add("装柜镇区管理", "BYManageInfoSystem.Frm_ZhuangGuiSite");
            dicCSharpBase.Add("DHL国外地区管理", "BYManageInfoSystem.Frm_DHLCountry");
            dicCSharpBase.Add("打折系数管理", "BYManageInfoSystem.Form_DiscountMgr");
            dicCSharpBase.Add("商检汇率管理", "BYManageInfoSystem.Form_SJHuiLvTabMgr");
            dicCSharpBase.Add("备案资料清单设定", "BYManageInfoSystem.Frm_BackQingDan");
            m_dicFormText2FormTypeName.Add("资料管理", dicCSharpBase);

            Dictionary<string, string> dicCSharpProvider = new Dictionary<string, string>();
            dicCSharpProvider.Add("拖车公司管理", "BYManageInfoSystem.Frm_ProviderTrailer");
            dicCSharpProvider.Add("报关行管理", "BYManageInfoSystem.Frm_SeaGateComp");
            dicCSharpProvider.Add("单证公司管理", "BYManageInfoSystem.Frm_SheetBookComp");
            dicCSharpProvider.Add("香港船务公司管理", "BYManageInfoSystem.Frm_HKShipComp");
            dicCSharpProvider.Add("快递公司管理", "BYManageInfoSystem.Frm_DHLInfo");
            dicCSharpProvider.Add("香港运输公司管理", "BYManageInfoSystem.Frm_RecvGoodsComp");
            m_dicFormText2FormTypeName.Add("供应商资料管理", dicCSharpProvider);

            Dictionary<string, string> dicOtherCSharpBase = new Dictionary<string, string>();
            dicOtherCSharpBase.Add("收货单位管理", "BYManageInfoSystem.Frm_RecvGoodsComp");
            dicOtherCSharpBase.Add("起运国及装运港管理", "BYManageInfoSystem.Frm_SendCountryAndPort");
            dicOtherCSharpBase.Add("包装种类，签订地点运输方式及柜型", "BYManageInfoSystem.Frm_BQYGInfo");
            dicOtherCSharpBase.Add("码头管理", "BYManageInfoSystem.Frm_PortInfo");
            dicOtherCSharpBase.Add("计量单位管理", "BYManageInfoSystem.Frm_DanWei");
            dicOtherCSharpBase.Add("目的国家管理", "BYManageInfoSystem.Frm_SourceNation");
            dicOtherCSharpBase.Add("币种管理", "BYManageInfoSystem.Frm_BiZhi");
            dicOtherCSharpBase.Add("海关管理", "BYManageInfoSystem.Frm_HaiGuan");
            m_dicFormText2FormTypeName.Add("其他资料管理", dicOtherCSharpBase);

            Dictionary<string, string> dicTiDan = new Dictionary<string, string>();
            dicTiDan.Add("提单模板管理", "BYManageInfoSystem.Frm_TiDanTemplete");
            dicTiDan.Add("提单Shipper管理", "BYManageInfoSystem.Frm_TiDanShipper");
            dicTiDan.Add("提单目的国家港口管理", "BYManageInfoSystem.Frm_TiDanMDCountryPort");
            dicTiDan.Add("提单目的国家Consignee管理", "BYManageInfoSystem.Frm_TiDanConsignee");
            dicTiDan.Add("提单目的国家DeliveryAgent管理", "BYManageInfoSystem.Frm_TiDanDeliveryAgentTab");
            dicTiDan.Add("提单管理", "BYManageInfoSystem.Frm_TiDanMng");

            m_dicFormText2FormTypeName.Add("提单记录管理", dicTiDan);

            Dictionary<string, string> dicBusiness = new Dictionary<string, string>();
            dicBusiness.Add("派单管理", "BYManageInfoSystem.Frm_ItemNewOrder");
            dicBusiness.Add("商检装箱单管理", "BYManageInfoSystem.Frm_CommerCheckFillBoxSheet");
            dicBusiness.Add("商检出口合同及发票", "BYManageInfoSystem.Frm_CommerCheckOutPutContract");
            dicBusiness.Add("购货合同草稿", "BYManageInfoSystem.Frm_CommerCheckBuyGoodsContract");
            dicBusiness.Add("派车单管理", "BYManageInfoSystem.Frm_DispatchCarSheet_New");
            dicBusiness.Add("报关装箱单", "BYManageInfoSystem.Frm_SeaGateFillBoxSheet");
            dicBusiness.Add("报关出口合同及发票", "BYManageInfoSystem.Frm_SeaGateOutPutContract");
            dicBusiness.Add("广东省出口商品统一发票", "BYManageInfoSystem.Frm_GDTYInvoice");
            dicBusiness.Add("合同批量打印", "BYManageInfoSystem.Frm_ContractBatchPrint");
            m_dicFormText2FormTypeName.Add("业务管理", dicBusiness);

            Dictionary<string, string> dicBackMaterial = new Dictionary<string, string>();
            dicBackMaterial.Add("寄往报关行单证登记表", "BYManageInfoSystem.Frm_PostToBGSheetReg");
            dicBackMaterial.Add("综合登记表", "BYManageInfoSystem.Frm_RetrieveInfoGeneral");
            dicBackMaterial.Add("外汇核销单还单登记表", "BYManageInfoSystem.Frm_ReturnRegSheet");
            dicBackMaterial.Add("合同编号明细表", "BYManageInfoSystem.Frm_PaidanRegisterDetail");
            dicBackMaterial.Add("报关单出货登记表", "BYManageInfoSystem.Frm_BGDOutGoodsRegSheet");
            dicBackMaterial.Add("交财务退税资料情况表", "BYManageInfoSystem.Frm_BackTaxRegSheet");
            dicBackMaterial.Add("缺合同登记表", "BYManageInfoSystem.Frm_ShortOfContractRegSheet");
            dicBackMaterial.Add("缺提单登记表", "BYManageInfoSystem.Frm_ShortofTDRegSheet");
            dicBackMaterial.Add("委托书明细表", "BYManageInfoSystem.Frm_WeituoShuSheet");
            dicBackMaterial.Add("资料出错记录", "BYManageInfoSystem.Frm_MeterialErrorRegSheet");
            dicBackMaterial.Add("欠提单委托书汇总表", "BYManageInfoSystem.Frm_ShortTDAndWeiTuoShuSum");
            dicBackMaterial.Add("备案资料回收登记表", "BYManageInfoSystem.Frm_BackRecoveryMaterialResgistTab");
            dicBackMaterial.Add("备案资料回收日期对应表", "BYManageInfoSystem.Frm_BackRecoveryDateCorrespondTab");
            m_dicFormText2FormTypeName.Add("回收资料", dicBackMaterial);

            Dictionary<string, string> dicFin = new Dictionary<string, string>();
            dicFin.Add("总财务收款明细表管理", "BYManageInfoSystem.Frm_RecvMoneyDetailSheet_New");
            dicFin.Add("增值税发票记录表管理", "BYManageInfoSystem.Frm_FinInvoiceRecordNew");
            dicFin.Add("财务增值税发票汇总表", "BYManageInfoSystem.Frm_FinInvoiceSummary");
            dicFin.Add("审票记录明细", "BYManageInfoSystem.Frm_FinInvoiceCheckRec");
            dicFin.Add("部门收款及付款明细表管理", "BYManageInfoSystem.Frm_PayAndRecvTab");
            dicFin.Add("收款明细补充表", "BYManageInfoSystem.Frm_RecvMoneyPayTaxAuxiliary_New");
            dicFin.Add("审票明细补充表", "BYManageInfoSystem.Frm_FinCheckInvoiceRecordDetailAuxiliaryTab_New");
            dicFin.Add("工厂往来表", "BYManageInfoSystem.Frm_FacComeAndGoReg_Newest");
            dicFin.Add("工厂往来补丁表", "BYManageInfoSystem.Frm_FinComeAndGoPackingTab");
            dicFin.Add("收齐资料交财务", "BYManageInfoSystem.Frm_SQZL2CW");
            dicFin.Add("工厂对账单", "BYManageInfoSystem.Frm_FinFacCheckSheetNew");
            dicFin.Add("工厂出货金额汇总", "BYManageInfoSystem.Frm_FactoryOutGoodsMoneyStat");
            dicFin.Add("信用证登记表", "BYManageInfoSystem.Frm_CreditCardRegister");
            dicFin.Add("贸易银行管理", "BYManageInfoSystem.Frm_InternationalTradeBank");
            dicFin.Add("收款方式管理", "BYManageInfoSystem.Frm_FinRecvMoneyWay");
            dicFin.Add("信用证收入", "BYManageInfoSystem.Frm_CreditCardIncome");
            
            m_dicFormText2FormTypeName.Add("财务管理", dicFin);

            

            Dictionary<string, string> dicFeePrice = new Dictionary<string, string>();
            dicFeePrice.Add("报关费明细录入", "BYManageInfoSystem.Frm_FeeBG_BGFee");
            dicFeePrice.Add("加页费明细录入", "BYManageInfoSystem.Frm_FeeBG_JYFee");
            dicFeePrice.Add("连柜费明细录入", "BYManageInfoSystem.Frm_FeeBG_LGFee");
            dicFeePrice.Add("通关单费明细录入", "BYManageInfoSystem.Frm_FeeBG_TGDFee");
            dicFeePrice.Add("港口建设费明细录入", "BYManageInfoSystem.Frm_FeeBG_GKJSFee");
            dicFeePrice.Add("单证费明细录入", "BYManageInfoSystem.Frm_DZFee");
            dicFeePrice.Add("运输费明细录入", "BYManageInfoSystem.Frm_FeeYS_YSFee");
            dicFeePrice.Add("拼柜费明细录入", "BYManageInfoSystem.Frm_FeeYS_PGFee");
            dicFeePrice.Add("超重费明细录入", "BYManageInfoSystem.Frm_FeeYS_CGFee");
            dicFeePrice.Add("过磅费明细录入", "BYManageInfoSystem.Frm_FeeYS_GBFee");
            dicFeePrice.Add("商检费明细录入", "BYManageInfoSystem.Frm_SJFee");
            dicFeePrice.Add("DHL费明细录入", "BYManageInfoSystem.Frm_DHLFee");
  
            m_dicFormText2FormTypeName.Add("费用定价管理", dicFeePrice);



            Dictionary<string, string> dicFeeShouldRecvPay = new Dictionary<string, string>();
            dicFeeShouldRecvPay.Add("工厂月度费用对帐单-非运输类", "BYManageInfoSystem.Frm_FeeFacCheckSheet");
            dicFeeShouldRecvPay.Add("应收应付费用汇总-非运输类", "BYManageInfoSystem.Frm_RecvFacFee_New2");
            dicFeeShouldRecvPay.Add("应收费用锁定", "BYManageInfoSystem.Frm_FeeLock");
            dicFeeShouldRecvPay.Add("其他票据明细表", "BYManageInfoSystem.Frm_FeeOtherInvoice");
            dicFeeShouldRecvPay.Add("百业票据明细表", "BYManageInfoSystem.Frm_FeeBYInvoice");
            dicFeeShouldRecvPay.Add("票据汇总", "BYManageInfoSystem.Frm_FeeInvoiceAndRecvGeneralTab");


            m_dicFormText2FormTypeName.Add("费用管理-应收应付", dicFeeShouldRecvPay);

    

            Dictionary<string, string> dicFeeTrueRecvPay = new Dictionary<string, string>();
            dicFeeTrueRecvPay.Add("实收费用汇总-非运输类", "BYManageInfoSystem.Frm_FeeBankRecvMoneyRecordTab_Pri");
            dicFeeTrueRecvPay.Add("实付费用汇总-非运输类", "BYManageInfoSystem.Frm_TruePaySummaryTab");
            dicFeeTrueRecvPay.Add("应收实收费用-非运输类", "BYManageInfoSystem.Frm_FeeShouldRecvTrueRecvTab");
            dicFeeTrueRecvPay.Add("实收费用锁定", "BYManageInfoSystem.Frm_FeeTrueReceiveLock");
            dicFeeTrueRecvPay.Add("实付费用锁定", "BYManageInfoSystem.Frm_FeeTruePayLock");
            dicFeeTrueRecvPay.Add("实收实付收支表1-非运输类", "BYManageInfoSystem.Frm_FeeShouldRecvTrueRecvSheet1");
            dicFeeTrueRecvPay.Add("实收实付收支表2-非运输类", "BYManageInfoSystem.Frm_FeeShouldRecvTrueRecvSheet2");


            m_dicFormText2FormTypeName.Add("费用管理-实收实付", dicFeeTrueRecvPay);

            Dictionary<string, string> dicFee = new Dictionary<string, string>();
            dicFee.Add("商检", "BYManageInfoSystem.Frm_FeeSJTruePayTab");
            dicFee.Add("报关", "BYManageInfoSystem.Frm_FeeBGTruePayTab");
            dicFee.Add("报关-对帐版", "BYManageInfoSystem.Frm_FeeBGTruePayInput");
            dicFee.Add("船务-大陆", "BYManageInfoSystem.Frm_FeeDLCWTruePayTab");
            dicFee.Add("船务-香港", "BYManageInfoSystem.Frm_FeeHKCWTruePayTab");
            dicFee.Add("运输费用", "BYManageInfoSystem.Frm_FeeDLYSTruePayTab");
            dicFee.Add("运输-香港", "BYManageInfoSystem.Frm_FeeHKYSTruePayTab");
            dicFee.Add("快递", "BYManageInfoSystem.Frm_FeeDHLTruePayTab");
            dicFee.Add("纸箱证", "BYManageInfoSystem.Frm_FeeZXZTruePayTab");
            dicFee.Add("检测费", "BYManageInfoSystem.Frm_FeeJCFTruePayTab");
            dicFee.Add("单证", "BYManageInfoSystem.Frm_FeeDZTruePayTab");
            dicFee.Add("特殊费", "BYManageInfoSystem.Frm_FeeSpecialRegisterTab");
            m_dicFormText2FormTypeName.Add("费用明细", dicFee);

            Dictionary<string, string> dicLog = new Dictionary<string, string>();
            dicLog.Add("日志", "BYManageInfoSystem.Frm_OperLog");

            m_dicFormText2FormTypeName.Add("日志管理", dicLog);
        }

        //初始化一次每次新增模块时调用
        private void InitFirstLevelFun()
        {

            List<FunctionInfo> list = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetAllFirstLevelFunctions();
            List<string> listName = new List<string>();
            foreach (FunctionInfo f in list)
            {
                listName.Add(f.Name);
            }
            foreach (string strTemp in m_dicFormText2FormTypeName.Keys)
            {
                if (listName.Contains(strTemp))
                    continue;
                FunctionInfo info = new FunctionInfo();
                info.Name = strTemp;
                info.PID = -1;
                info.ControlID = "";
                info.SystemType_ID = "WareMis";
                function.Insert(info);
            }
        }
        //初始化一次每次新增模块时调用
        private void InitSecondLevelFun()
        {


            List<FunctionInfo> list = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetAllFunctions();
            List<string> listName = new List<string>();
            foreach (FunctionInfo f in list)
            {
                listName.Add(f.Name);
            }

            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                FunctionInfo fi = function.FindSingle("name='" + strModule + "'");
                foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[strModule].Keys)
                {
                    if (listName.Contains(strItem))
                        continue;
                    FunctionInfo info = new FunctionInfo();
                    info.Name = strItem;
                    info.PID = fi.ID;
                    info.ControlID = Frm_Main.m_dicFormText2FormTypeName[strModule][strItem];
                    info.SystemType_ID = "WareMis";
                    int nID = function.Insert2(info);

                    FunctionInfo infoAdd = new FunctionInfo();
                    infoAdd.Name = strItem + "_增加";
                    infoAdd.PID = nID;
                    infoAdd.ControlID = "";
                    infoAdd.SystemType_ID = "WareMis";
                    function.Insert(infoAdd);

                    FunctionInfo infoMod = new FunctionInfo();
                    infoMod.Name = strItem + "_修改";
                    infoMod.PID = nID;
                    infoMod.ControlID = "";
                    infoMod.SystemType_ID = "WareMis";
                    function.Insert(infoMod);

                    FunctionInfo infoDel = new FunctionInfo();
                    infoDel.Name = strItem + "_删除";
                    infoDel.PID = nID;
                    infoDel.ControlID = "";
                    infoDel.SystemType_ID = "WareMis";
                    function.Insert(infoDel);
                }
            }
        }
        private string GetParentName(FunctionInfo functionInfoChild)
        {
            foreach (FunctionInfo functionInfo in m_lstOneLevelFunRuntime)
            {
                if (functionInfo.ID == functionInfoChild.PID)
                {
                    return functionInfo.Name;
                }
            }
            return "";
        }
        private void InitFormText2FormTypeNameDic()
        {
            m_lstOneLevelFunRuntime.Clear();
            m_dicFormText2FormTypeName.Clear();
            m_UserFunList = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetFunctionsByUser(m_nLoginUserId, "WareMis");

            if (m_UserFunList != null && m_UserFunList.Count > 0)
            {

                foreach (FunctionInfo functionInfo in m_UserFunList)
                {
                    if (functionInfo.PID == -1)
                    {
                        Dictionary<string, string> dicCSharpBase = new Dictionary<string, string>();
                        m_dicFormText2FormTypeName.Add(functionInfo.Name, dicCSharpBase);
                        m_lstOneLevelFunRuntime.Add(functionInfo);
                    }
                }
              
                foreach (FunctionInfo functionInfoFather in m_lstOneLevelFunRuntime)
                {
                    foreach (FunctionInfo functionInfo in m_UserFunList)
                    {
                        if (functionInfo.PID == functionInfoFather.ID)
                        {
                            //m_dicFormText2FormTypeName.Keys
                            //string strTemp = GetParentName(functionInfo);
                            if (m_dicFormText2FormTypeName.Keys.Contains(functionInfoFather.Name))
                                m_dicFormText2FormTypeName[functionInfoFather.Name].Add(functionInfo.Name, functionInfo.ControlID);


                        }
                    }
                }

            }

            return;


        }

        private DockContent FindDocument(string text)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.DockingMdi)
            {
                foreach (Form form in MdiChildren)
                {
                    if (form.Text == text)
                    {
                        return form as DockContent;
                    }
                }

                return null;
            }
            else
            {
                foreach (DockContent content in dockPanel.Documents)
                {
                    if (content.DockHandler.TabText == text)
                    {
                        return content;
                    }
                }

                return null;
            }
        }

        public void ShowContent(DockContent frm)
        {
            frm.Show(this.dockPanel);
            frm.Focus();
            frm.BringToFront();
        }
        private string GetClassByName(string strName)
        {
            string strTemp = "";
            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[strModule].Keys)
                {
                    if (strItem == strName)
                    {
                        strTemp = Frm_Main.m_dicFormText2FormTypeName[strModule][strItem];
                        break;
                    }
                }
            }
            foreach (string strItem in Frm_Main.m_dicModuleHelpWnd.Keys)
            {
                if (strItem == strName)
                {
                    strTemp = Frm_Main.m_dicModuleHelpWnd[strItem];
                    break;
                }
            }
            return strTemp;
        }

        private bool HaveFun(string strTemp)
        {
            bool bRet = false;
            if (m_dicModuleHelpWnd.Keys.Contains(strTemp))
            {
                return true;
            }

            foreach (string strModule in m_dicFormText2FormTypeName.Keys)
            {

                if (m_dicFormText2FormTypeName[strModule].Keys.Contains(strTemp))
                {
                    bRet = true;
                    break;
                }

            }
            return bRet;
        }

        private Object ShowContentEx(string strTemp)
        {
            Object mdiChild = null;
            if (strTemp == "主页")
            {
                Dictionary<string, string> dicHome = new Dictionary<string, string>();
                foreach (string strModule in m_dicFormText2FormTypeName.Keys)
                {

                    dicHome.Add(strModule, strModule);

                }

                mdiChild = new Frm_Home2(dicHome, strTemp);
                return mdiChild;
                //break;
            }
            else if (m_dicModuleHelpWnd.Keys.Contains(strTemp))
            {
                mdiChild = new Frm_Home2(m_dicFormText2FormTypeName[strTemp], strTemp);
                return mdiChild;
            }
            Assembly assembly = Assembly.GetExecutingAssembly();
            //test(assembly);

            Type typForm = assembly.GetType(strTemp);
            //关于InvokeMember用法，不明白的可以查看：http://msdn.microsoft.com/zh-cn/library/de3dhzwy(VS.80).aspx
            mdiChild = typForm.InvokeMember(
               null,
                BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance,
               null,
               null,
               null);

            return mdiChild;
        }

        public DockContent ShowContent(string caption/*, Type formType*/)
        {

            DockContent frm = FindDocument(caption);

            if (frm == null)
            {
                //DockContent currentMdiChild = null;
                //Assembly assembly = Assembly.GetExecutingAssembly();
                //if (!m_dicFormText2FormTypeName.ContainsKey(caption))
                //    return frm;
                //Type typForm = assembly.GetType(m_dicFormText2FormTypeName[caption]);
                string strTemp = caption;
                if (caption != "主页")
                {
                    if (!HaveFun(caption))
                        return null;
                    strTemp = GetClassByName(caption);
                    if (strTemp == "")
                        return null;
                }
      


                Object mdiChild = ShowContentEx(strTemp);

                if (mdiChild != null)
                {
                    frm = mdiChild as DockContent;
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;

                }
            }
            
            frm.Show(this.dockPanel);
            frm.Focus();
            frm.BringToFront();
            return frm;
        }
        private void Frm_Main_Load(object sender, EventArgs e)
        {
            DisableCloseButton(this);
            //try
            //{


            //    //Frm_LoginNew frm_login = new Frm_LoginNew();

            //    //if (frm_login.ShowDialog() == DialogResult.OK)
            //    //{
            //    //    int a = 0;
            //    //}
            //    //else
            //    //{
            //    //    int b = 0;
            //    //    Application.Exit();
            //    //    return;
            //    //}
            //    InitFormText2FormTypeNameDic();//获取权限
            //    if (Frm_MainNew.m_dicFormText2FormTypeName.Count != 0)
            //    {
            //        mainToolWin = new Frm_MainToolWindowNew();
            //        mainToolWin.Show(this.dockPanel, DockState.DockLeft);
            //        InitMenuItem();
            //       // InitToolStrip();

            //    }



            //    this.dockPanel.DockLeftPortion = 0.17;
            //    ShowContent("主页");
            //}
            //catch (System.Exception ex)
            //{
            //    MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}








 

            m_nContractSelectValue = m_bllPaidanRegisterTab.GetMaxId() - 1;
            //this.dockPanel.BackgroundImage = null;
            m_lstPermitPerson.Add("吴婉玲");
            m_lstPermitPerson.Add("卢丽平");
            m_lstPermitPerson.Add("钟运甜");
            m_lstPermitPerson.Add("陈洁薇");
            m_lstPermitPerson.Add("林淦坤");
            m_lstPermitPerson.Add("赖泽文");
            m_lstPermitPerson.Add("梁青媚");
            m_lstPermitPerson.Add("肖丽新");
            m_lstPermitPerson.Add("宋波");
            InitActivePrinterName();
            DataSet ds = m_bllVersionTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                string strVer = ds.Tables[0].Rows[0]["VersionNo"].ToString();
                UpdaterConfigurationView updateCfgView = new UpdaterConfigurationView();
                string strTemp = updateCfgView.Version;
                if (strVer != strTemp)
                {
                    MessageBox.Show("请使用最新版本的程序登录！" + "数据库最新版本" + strVer + "您当前版本" + strTemp, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Application.Exit();
                    return;
                }
                else
                {
                    this.Text += "Ver" + strVer;
                }

            }


            Frm_LoginNew frm_login = new Frm_LoginNew();

            if (frm_login.ShowDialog() == DialogResult.OK)
            {
                m_strLoginUser = frm_login.comboBoxOrderPerson.Text;
                this.Text += @"-" + m_strLoginUser;

                //ds = m_bllT_ACL_User.GetList("T_ACL_User.Name = '" + m_strLoginUser + "'");
                //if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    //m_nLoginUserId = Convert.ToInt32(ds.Tables[0].Rows[0]["UserPasswordTabID"].ToString());
                    //Frm_Main.Notify("登录成功", "欢迎" + m_strLoginUser, 300, 200, 3000);
                    m_bLoginSuccess = true;
                    //  m_log = new Log(m_strLoginUser);
                    this.timer1.Start();
                    // backgroundWorker1.RunWorkerAsync();
                    DGBY.Model.DiscountTab modelDiscountTab = m_bllDiscountTab.GetModel(1);
                    m_dtDiscountFactor = modelDiscountTab.DiscountFactor;

                    bgModifySJShouldPayMonth.RunWorkerAsync();
                }
                //else
                //{
                //    Application.Exit();
                //}

                bool bTest = m_bCompleteVer;

            }
            else
            {
                Application.Exit();
            }

            DateTime dtServer = GetCurrentSysDateTime();
            DateTime dtClient = System.DateTime.Now.Date;
            if (!dtClient.Equals(dtServer))
            {
                MessageBox.Show("您本机时间和服务器时间不一致！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }

            if (Frm_Main.m_strLoginUser == "宋波")
            {
                TryUpdateVersion();
            }
            InitFormText2FormTypeNameDic();//获取权限
            if (Frm_Main.m_dicFormText2FormTypeName.Count != 0)
            {
                mainToolWin = new Frm_MainToolWindowNew();
                mainToolWin.Show(this.dockPanel, DockState.DockLeft);
                InitMenuItem();
                InitToolStrip();

            }



            this.dockPanel.DockLeftPortion = 0.17;
            //ShowContent("主页");
            //ShowContent("主页");
            //mainToolWin = new Frm_MainToolWindow();
            //mainToolWin.Show(this.dockPanel, DockState.DockLeft);
            //InitFormText2FormTypeNameDic();

            //this.dockPanel.DockLeftPortion = 0.17;


            //if (Frm_Main.m_bCompleteVer == false)
            //    this.提单管理ToolStripMenuItem.Visible = false;
            //else
            //    this.提单管理ToolStripMenuItem.Visible = true;
  
        }
        private void InitToolStrip()
        {
            //int nIndex = 0;
            //foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            //{
            //    //ToolStrip ts = new ToolStrip();
            //    ToolStripButton tsb = new ToolStripButton(strModule);
            //    tsb.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
            //    tsb.Image = this.imageList.Images[nIndex++];//从ImageList里指定或其他方式指定
            //    tsb.Click += new EventHandler(tsb_Click);
            //    toolStrip1.Items.Add(tsb);
            //}
            foreach (ToolStripItem mi in toolStrip1.Items)
            {

                if (mi.GetType() == typeof(ToolStripButton))
                {
                    if (mi.Text != "权限管理" && mi.Text != "套打打印机设置" && mi.Text != "系统数据处理")
                    mi.Visible = HaveFun(mi.Text);
                }
            }

        }
        void tsb_Click(object sender, EventArgs e)
        {
            ToolStripButton tsmi = (ToolStripButton)sender;
            ShowContent(tsmi.Text.ToString());
            return;
        }
        private void InitMenuItem()
        {
            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Name = strModule; //menuname
                item.Text = strModule;
                //menuStrip1.Items[item.Name].Enabled = true;
                InitSubMenuItem(item);
                menuStripMain.Items.Add(item);
            }

        }
        private void InitSubMenuItem(ToolStripItem item)
        {
            string mname = item.Name;
            ToolStripMenuItem pItem = (ToolStripMenuItem)item;
            //根据父菜单项加载子菜单


            foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[mname].Keys)
            {
                try
                {
                    ToolStripMenuItem subItem = new ToolStripMenuItem();
                    subItem.Name = strItem; //menuname
                    subItem.Text = strItem;
                    subItem.Click += new EventHandler(subItem_Click);
                    pItem.DropDownItems.Add(subItem);
                    //pItem.DropDownItems[strItem].Enabled = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }

        }

        void subItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            ShowContent(tsmi.Text.ToString());
            return;
        }
        //public static void Log2DB(string strModuleName, string strOperName, string DanjuNameOrNo)
        //{
        //    //TrainingDB.Model.CK_OperLogTab modelCK_OperLogTab = new TrainingDB.Model.CK_OperLogTab();
        //    //modelCK_OperLogTab.CK_OperDate = System.DateTime.Now;
        //    //modelCK_OperLogTab.CK_OperUserID = m_nLoginUserId;
        //    //modelCK_OperLogTab.CK_OperName = strOperName;
        //    //modelCK_OperLogTab.CK_ModuleName = strModuleName;
        //    //modelCK_OperLogTab.CK_DanjuNameOrNo = DanjuNameOrNo;

        //    //m_bllDG_OperLogTab.Add(modelCK_OperLogTab);
        //}
        private void InitModuleHelpWnd()
        {
            foreach (string strModule in m_dicFormText2FormTypeName.Keys)
            {

                m_dicModuleHelpWnd.Add(strModule, strModule);

            }
            //m_dicModuleHelpWnd.Add("教学管理", "CKNetFrameWork.Frm_EducationMgr");
            //m_dicModuleHelpWnd.Add("主页", "CKNetFrameWork.Frm_Home");
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Frm_DataProcess frm_DataProcess = new Frm_DataProcess();
            frm_DataProcess.StartPosition = FormStartPosition.CenterScreen;
            frm_DataProcess.ShowDialog();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            Frm_PrinterSetting frm_PrinterSetting = new Frm_PrinterSetting();
            frm_PrinterSetting.StartPosition = FormStartPosition.CenterScreen;
            frm_PrinterSetting.ShowDialog();
        }

        private void bgModifySJShouldPayMonth_DoWork(object sender, DoWorkEventArgs e)
        {
            bool bModify = false;
            DateTime dtNow = GetCurrentSysDateTime();

            DataSet dsSjList =m_bllFeeSJTruePayTab.GetNuSetTongjDateList();
            if (dsSjList.Tables.Count > 0 && dsSjList.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dsSjList.Tables[0].Rows.Count; i++)
                {
                    int nFeeSJTruePayTabID = Convert.ToInt32(dsSjList.Tables[0].Rows[i]["FeeSJTruePayTabID"].ToString());

                    DGBY.Model.FeeSJTruePayTab modelSJTruePayTabOld = m_bllFeeSJTruePayTab.GetModel(nFeeSJTruePayTabID);
                    if (null == modelSJTruePayTabOld || 0 != modelSJTruePayTabOld.ShouldPayMonth)
                        continue;

                    bModify = false;

                    DateTime dtPaiDanDate = Convert.ToDateTime(dsSjList.Tables[0].Rows[i]["签订日期"].ToString());
                    TimeSpan dt = dtNow - dtPaiDanDate;

                    if ("家具" == dsSjList.Tables[0].Rows[0]["货品种类"].ToString())
                    {
                        if (dt.Days > 21)
                        {
                            modelSJTruePayTabOld.ShouldPayMonth = dtNow.Date.Year * 100 + dtNow.Date.Month;
                            bModify = true;
                        }
                    }
                    else
                    {
                        if (dt.Days > 60)
                        {
                            modelSJTruePayTabOld.ShouldPayMonth = dtNow.Date.Year * 100 + dtNow.Date.Month;
                            bModify = true;
                        }
                    }

                    if (bModify)
                    {
                        m_bllFeeSJTruePayTab.Update(modelSJTruePayTabOld);
                        Frm_Main.Log2DB(this.Text, "修改商检应收费用计提年月", nFeeSJTruePayTabID.ToString());
                    }   
                }
            }
        }

        //获得当前系统时间
        public static DateTime GetCurrentSysDateTime()
        {
            if (m_dtServerSingle.Year == 1900)
            {
                m_dtServerSingle = m_bllPaidanRegisterTab.GetSysDateTime();
            }

            return m_dtServerSingle.Date;
        }
    }
}